import {
  loginByUsername,
  logout,
  getUserInfo,
  loginByWechat,
  getUserAvatar
} from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { Message, MessageBox } from "element-ui";
import { rootsUrl } from "@/utils";
import { getAvatar, setAvatar, removeAvatar} from "@/utils/avatar"

const user = {
  state: {
    email: "",
    userId: "",
    userName: "",
    sex: null,
    mobile: null,
    wechat: null,
    code: null,
    age: null,
    job: "",
    qq: "",
    avatar: "",
    codeType: "",
    microBlog: "",
    token: getToken(),
    dialogLogin: false,
    dialogNeedLogin: false
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId;
    },
    SET_EMAIL: (state, email) => {
      state.email = email || "";
    },
    SET_CODE: (state, code) => {
      state.code = code || "";
    },
    SET_CODE_TYPE: (state, codeType) => {
      state.codeType = codeType || "";
    },
    SET_USER_NAME: (state, name) => {
      state.userName = name || "";
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar || "";
    },
    SET_AGE: (state, age) => {
      state.age = age || "";
    },
    SET_MOBILE: (state, mobile) => {
      state.mobile = mobile || "";
    },
    SET_SEX: (state, sex) => {
      state.sex = sex || "";
    },
    SET_JOB: (state, job) => {
      state.job = job || "";
    },
    SET_QQ: (state, qq) => {
      state.qq = qq;
    },
    SET_WECHAT: (state, wechat) => {
      state.wechat = wechat;
    },
    SET_MICRO_BLOG: (state, microBlog) => {
      state.microBlog = microBlog || "";
    },
    SET_DIALOG_LOGIN: (state, isShow) => {
      state.dialogLogin = isShow;
    },
    SET_DIALOG_NEED_LOGIN: (state, isShow) => {
      state.dialogNeedLogin = isShow;
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit, dispatch }, userInfo) {
      const userId = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        loginByUsername(userId, userInfo.password)
          .then(response => {
            if (response.flag == -1) {
              // Message({
              //   type: "error",
              //   message: response.msg
              // });

              MessageBox.alert(response.msg, "提示", {
                confirmButtonText: "确定",
                type: "warning"
              });
              return false;
            }
            const data = response.data;
            setToken(data.token);
            commit("SET_EMAIL", data.email);
            commit("SET_USER_ID", data.userId);
            commit("SET_USER_NAME", data.userName);
            commit("SET_SEX", data.sex);
            commit("SET_MOBILE", data.mobile);
            commit("SET_WECHAT", data.wechat);
            commit("SET_CODE", data.identityId);
            commit("SET_AGE", data.uage);
            commit("SET_JOB", data.uword);
            commit("SET_QQ", data.uqq);
            commit("SET_CODE_TYPE", data.idType);
            commit("SET_TOKEN", data.token);
            commit("SET_MICRO_BLOG", data.microBlog);
            commit("SET_DIALOG_LOGIN", false);
            commit(
              "SET_AVATAR",
              `${rootsUrl[0]}/museum/gatewayUser/showUserHead.shtml?userId=` +
                data.userId
            );
            Message({
              message: `${data.userName || ""}你好，欢迎来到长沙博物馆`,
              type: "success"
            });
            dispatch("GetUserAvatar");
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetUserInfo({ commit, state, actions, dispatch }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token)
          .then(response => {
            // 当异常时
            if (response.flag == -1) {
              Message({
                type: "error",
                message: response.msg,
                showClose: true
              });
              return false;
            }

            if (response.flag == 0) {
              return false;
              Message({
                type: "warning",
                message: response.msg,
                showClose: true
              });
            }

            if (response.flag == 1) {
              const data = response.data;
              commit("SET_EMAIL", data.email);
              commit("SET_USER_ID", data.userId);
              commit("SET_USER_NAME", data.userName);
              commit("SET_SEX", data.sex);
              commit("SET_MOBILE", data.mobile);
              commit("SET_WECHAT", data.wechat);
              commit("SET_CODE", data.identityId);
              commit("SET_AGE", data.uage);
              commit("SET_JOB", data.uword);
              commit("SET_QQ", data.uqq);
              commit("SET_CODE_TYPE", data.idType);
              commit("SET_MICRO_BLOG", data.microBlog);
              commit("SET_DIALOG_LOGIN", false);
              // commit(
              //   "SET_AVATAR",
              //   `${rootsUrl[0]}/museum/gatewayUser/showUserHead.shtml?userId=` +
              //     data.userId
              // );
              dispatch("GetUserAvatar");
              resolve();
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 获取用户头像
    GetUserAvatar({ commit, state }) {
      return new Promise((resolve, reject) => {
        if(!state.wechat){
          commit(
            "SET_AVATAR",
            `${rootsUrl[0]}/museum/gatewayUser/showUserHead.shtml?userId=` +
              state.userId +
              "&t=" +
              Math.random()
          );
        } else {
          if(getAvatar()){
            commit("SET_AVATAR",getAvatar())
          }
        }
        resolve();
      });
    },

    // 第三方验证登录
    LoginByWechat({ commit, state, dispatch }, code) {
      return new Promise((resolve, reject) => {
        commit("SET_CODE", code);
        loginByWechat(code)
          .then(response => {
            if (response.flag == -1) {
              Message({
                type: "error",
                message: response.msg
              });
              return false;
            }
            const data = response.data;
            setToken(data.token);
            commit("SET_EMAIL", data.email);
            commit("SET_USER_ID", data.userId);
            commit("SET_USER_NAME", data.userName);
            commit("SET_SEX", data.sex);
            commit("SET_MOBILE", data.mobile);
            commit("SET_WECHAT", data.wechat);
            commit("SET_AVATAR", data.headimgurl);
            commit("SET_CODE", data.identityId);
            commit("SET_AGE", data.uage);
            commit("SET_JOB", data.uword);
            commit("SET_QQ", data.uqq);
            commit("SET_CODE_TYPE", data.idType);
            commit("SET_TOKEN", data.token);
            commit("SET_MICRO_BLOG", data.microBlog);
            setAvatar('Changbo-Avatar',data.headimgurl)
          })
          .catch(err => {
            console.log(err);
          });
      });
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        // logout(state.token)
        //   .then(() => {
        //     commit("SET_TOKEN", "");
        //     removeToken();
        //     commit("SET_USER_ID", "");
        //     resolve();
        //   })
        //   .catch(error => {
        //     reject(error);
        //   });
        commit("SET_TOKEN", "");
        removeToken();
        commit("SET_USER_ID", "");
        resolve();
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit("SET_USER_ID", "");
        removeToken();
        resolve();
      });
    },

    // 动态修改权限
    ChangeRoles({ commit }, role) {
      return new Promise(resolve => {
        commit("SET_TOKEN", role);
        setToken(role);
        getUserInfo(role).then(response => {
          const data = response.data;
          commit("SET_ROLES", data.roles);
          commit("SET_NAME", data.name);
          commit("SET_AVATAR", data.avatar);
          commit("SET_INTRODUCTION", data.introduction);
          resolve();
        });
      });
    },

    // 打开登录框
    ToggleLoginDialog({ commit }, isShow) {
      commit("SET_DIALOG_LOGIN", isShow);
    },

    // 打开需要登录对话框
    ToggleNeedLogin({ commit }, isShow) {
      commit("SET_DIALOG_NEED_LOGIN", isShow);
    }
  }
};

export default user;
